import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { type CallToolResult, type GetPromptResult } from '@modelcontextprotocol/sdk/types';
import { z } from 'zod';
import { captureDataFromUrl } from './data-capture';
import { Logger } from '~/utils/logger';
import { iDocUrlRegex } from '~/utils/idoc';
import { designToCodePrompt } from '~/prompts/design-to-code';
import {
  DesignResource,
  designResourceTemplate,
  resourceUriPrefix,
  transientResourceStore,
} from './resource';
import { simplifyDesignJson } from '~/utils/simplify-design';

let mcpServer: McpServer = null;

const DesignDataToolName = 'get_design_specs_and_create_resource';

const toolInputSchema = z.object({
  // https://idoc.mucang.cn/app/Q4R8OUxZO0/develop/design/k78Z0XvYP0DK
  designUrl: z.string().describe('It should be a url like https://idoc.**/**'),
});

const promptInputSchema = z.object({
  designUrl: z.string().describe('iDoc 设计稿的完整 URL 地址'),
  framework: z.string().default('Vue3').describe('前端框架，默认为 Vue3'),
});

/** 优化的设计稿代码生成提示词处理器 */
async function designPromptHandler(params: {
  designUrl: string;
  framework: string;
}): Promise<GetPromptResult> {
  Logger.info(`[Prompt] 启动设计稿代码生成, URL: ${params.designUrl}`);

  return {
    messages: [
      {
        role: 'assistant',
        content: {
          type: 'text',
          text: designToCodePrompt(params.framework),
        },
      },
      {
        role: 'user',
        content: {
          type: 'text',
          text: `请将以下设计稿转化为前端代码：${params.designUrl} 使用 ${DesignDataToolName} 工具获取设计稿结构化数据`,
        },
      },
    ],
  };
}

export async function handleGetDesignResource(params: {
  designUrl: string;
}): Promise<CallToolResult> {
  try {
    Logger.info(`[Tool] 开始解析设计稿: ${params.designUrl}`);

    const originalJson = await captureDataFromUrl(params.designUrl);

    const { appId, designId } = iDocUrlRegex(params.designUrl);

    const resourceUri = `${resourceUriPrefix}${appId}-${designId}`.toLocaleLowerCase();

    // 根据选择的格式处理数据
    let mimeType = 'application/json'; // 'application/octet-stream'

    const optimizedData = simplifyDesignJson(originalJson);

    const record: DesignResource = {
      uri: resourceUri,
      name: `设计稿数据 - ${params.designUrl}`,
      description: `来自 ${params.designUrl} 的设计稿详细数据，包含组件结构、样式信息等`,
      mimeType,
      text: JSON.stringify(optimizedData, null, 2),
    };

    transientResourceStore.set(resourceUri, record);

    const isConnected = mcpServer ? mcpServer.isConnected() : false;

    if (isConnected) {
      mcpServer.sendResourceListChanged();

      mcpServer.resource('design-resource-template', resourceUri, function () {
        return {
          uri: record.uri,
          mimeType: record.mimeType,
          blob: record.blob,
        };
      });
    }

    Logger.info(`[Tool] 已创建资源: ${resourceUri}`);

    return {
      content: [
        {
          type: 'resource',
          description: `设计稿数据已成功解析并存储为 resource`,
          uri: resourceUri,
          resource: record,
        },
      ],
      isError: false,
    };
  } catch (error) {
    Logger.error(`[Tool] 解析设计稿失败: ${error}`);
    return {
      content: [
        {
          type: 'text',
          text: `❌ 解析设计稿失败：${error instanceof Error ? error.message : '未知错误'}`,
        },
      ],
      isError: true,
    };
  }
}

export function registerDesignDataTool(server: McpServer): void {
  mcpServer = server;

  server.registerTool(
    DesignDataToolName,
    {
      title: '获取设计稿数据并创建资源',
      description: `解析 iDoc 设计稿 URL，提取设计数据，并创建包含完整设计信息的临时资源。AI 助手需要读取返回的 resource uri 来获取具体的设计稿数据。`,
      inputSchema: toolInputSchema.shape,
    },
    handleGetDesignResource
  );

  server.registerPrompt(
    'generate-code-from-design',
    {
      title: '智能设计稿代码生成',
      description: '基于 iDoc 设计稿 URL，使用专业提示词指导，生成高质量、组件化的前端代码',
      argsSchema: promptInputSchema.shape,
    },
    designPromptHandler
  );

  // 注册资源模板 - 用于动态资源
  server.registerResource(
    'design-resource-template',
    designResourceTemplate,
    {
      name: '设计稿资源',
      description: '从 iDoc 设计稿提取的结构化数据资源',
      mimeType: 'application/octet-stream',
    },
    async (uri: URL) => {
      const uriString = uri.toString();
      Logger.info(`[Resource Template] 读取资源: ${uriString}`);

      // 从临时存储中获取资源
      const resource = transientResourceStore.get(uriString);

      if (!resource) {
        Logger.error(`[Resource] 资源未找到: ${uriString}`);
        throw new Error(`Resource not found: ${uriString}`);
      }

      Logger.info(`[Resource] 成功读取资源: ${uriString}`);

      return {
        contents: [
          {
            uri: resource.uri,
            mimeType: resource.mimeType,
            blob: resource.blob,
          },
        ],
      };
    }
  );
}
